package com.reliable.service.controller;

import com.reliable.api.dto.chatmessage.ChatMessageDTO;
import com.reliable.api.dto.chatmessage.ChatMessagePageDTO;
import com.reliable.api.dto.chatmessage.ChatMessageSessionDTO;
import com.reliable.api.param.chat.ChatMessageQueryPageParam;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.service.domain.ReliableTask;
import com.reliable.service.service.ChatMessageService;
import com.reliable.service.service.IReliableTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 聊天消息分页查询Controller
 */
@RestController
@RequestMapping("/reliable/chat")
@Api(value = "首页查询接口配置", tags = {"首页查询接口管理"})
public class ChatMessagePageController {
    
    @Autowired
    private ChatMessageService chatMessageService;
    
    @Autowired
    private IReliableTaskService taskService;
    
    /**
     * 分页查询聊天消息
     *
     * @param param 查询参数
     * @return 分页查询结果
     */
    @PostMapping("/list")
    @ApiOperation("分页查询聊天消息，通过条件")
    public AjaxResult list(@RequestBody ChatMessageQueryPageParam param) {
        ChatMessagePageDTO result = chatMessageService.findForHomePageWithTotal(
                param.getSessionId(),
                param.getKeyword(),
                param.getPageNum(),
                param.getPageSize()
        );
        
        // 获取所有唯一的taskId
        List<Long> taskIds = result.getRecords().stream()
                .map(ChatMessageDTO::getTaskId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());
        
        // 批量查询taskId到taskName的映射
        Map<Long, String> taskIdToNameMap = taskIds.stream()
                .collect(Collectors.toMap(
                        taskId -> taskId,
                        taskId -> {
                            ReliableTask task = taskService.selectReliableTaskById(taskId);
                            return task != null ? task.getTaskName() : "";
                        }
                ));
        
        // 将任务名称设置到每个记录中
        result.getRecords().forEach(record -> {
            if (record.getTaskId() != null) {
                record.setTaskName(taskIdToNameMap.get(record.getTaskId()));
            }
        });

        return AjaxResult.success(result);
    }

    /**
     * 通过sessionId查询聊天记录
     *
     * @param
     * @return 聊天记录列表
     */
    @PostMapping("/sessionInfo")
    @ApiOperation("通过sessionId查询聊天记录")
    public AjaxResult getSessionMessages(@RequestBody ChatMessageQueryPageParam param) {
        List<ChatMessageSessionDTO> result = chatMessageService.findSessionMessages(param.getSessionId(),param.getPageNum(),
                param.getPageSize());
        return AjaxResult.success(result);
    }
}